package com.project.base.baseproject.Activity.MainActivity;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.makeramen.roundedimageview.RoundedImageView;
import com.project.base.baseproject.Activity.LoginActivity.LoginActivity;
import com.project.base.baseproject.AppCustoms.ActionSheet.ActionSheet;
import com.project.base.baseproject.AppCustoms.LoadingUpView.LoadingDialog;
import com.project.base.baseproject.AppCustoms.MyApplication.MyApplication;
import com.project.base.baseproject.AppCustoms.Tool.StringUtil;
import com.project.base.baseproject.AppCustoms.Tool.ToastUtil;
import com.project.base.baseproject.ModelManager.Models.EventBusClass;
import com.project.base.baseproject.R;
import com.project.base.baseproject.Utikles.Constant.Constant;
import com.project.base.baseproject.Utikles.DiviceInfo.DiviceInfo;
import com.squareup.picasso.Picasso;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.BitmapCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

//主页
public class MainActivity extends AppCompatActivity {
    @BindView(R.id.user_avater) RoundedImageView userAvater;
    @BindView(R.id.user_name) TextView userName;
    //加载指示器
    LoadingDialog loadingDialog;
    //拍照临时图片路径
    File photoFile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_layout);
        loadingDialog = new LoadingDialog(this);
        //设置沉侵式状态栏
        StatusBarUtil.setColor(this, getResources().getColor(R.color.black),0);
        //绑定界面元素
        ButterKnife.bind(this);
        setCurrUserInfo();
        //监听数据库变化
        EventBus.getDefault().register(this);
    }
    //只要用户信息发生了改变，就会立马回调此方法
    private void setCurrUserInfo() {
        Picasso.with(this).load(MyApplication.userManager.user.getAvatar()).placeholder(R.drawable.ic_launcher).error(R.drawable.ic_launcher).into(userAvater);
        userName.setText(MyApplication.userManager.user.getName());
    }
    //监听EventBus事件
    @Subscribe @MainThread
    public void onEventMainThread(EventBusClass event) {
        //用户信息改变
        if(event.getType() == EventBusClass.UserInfoChangeEvent)
            setCurrUserInfo();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, Menu.FIRST + 1, 0, "修改名字");
        menu.add(Menu.NONE, Menu.FIRST + 2, 0, "修改头像");
        menu.add(Menu.NONE, Menu.FIRST + 3, 0, "退出登陆");
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //修改名字
        if(item.getItemId() == Menu.FIRST + 1) {
            //这里只需要做数据库的操作，UI更新交给EventBus
            MyApplication.userManager.user.setName("TheBloodeElfOver");
            MyApplication.userManager.updateUser(MyApplication.userManager.user);
        }
        //修改头像
        if(item.getItemId() == Menu.FIRST + 2) {
            ArrayList<String> arrayList1 = new ArrayList<>();
            arrayList1.add("选取相册图片");
            arrayList1.add("现在拍摄");
            final ActionSheet actionSheet1 = new ActionSheet(MainActivity.this,"上传图标",arrayList1);
            actionSheet1.setActionSheetClickListener(new ActionSheet.ActionSheetClickListener() {
                @Override
                public void onItemClick(View view, int index) {
                    actionSheet1.close();
                    //选择相册图片
                    if(index == 0) {
                        //调用系统选择
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, Constant.SINGLE_SELECT_IMAGE_REQUEST_CODE);
                    } else {//拍照
                        //检查有没有拍照权限
                        if(ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CAMERA,},5001);
                        } else {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            photoFile = new File(MyApplication.fileManager.baseFilePath,new Date().getTime()+".jpg");
                            Uri photoImageUri = FileProvider.getUriForFile(MainActivity.this, "com.project.base.baseproject.FileProvider",photoFile);//通过FileProvider创建一个content类型的Uri
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoImageUri);//将拍取的照片保存到指定URI
                            startActivityForResult(intent, Constant.SYSTEM_CAPTURE_REQUEST_CODE);
                        }
                    }
                }
            });
            actionSheet1.show();
        }
        if(item.getItemId() == Menu.FIRST + 3) {
            //改变当前登陆用户的guid为空
            MyApplication.identityManager.identity.user_guid = "";
            MyApplication.identityManager.saveAuthorizeData();
            //启动登陆界面
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 5001) {
            int resultCode = grantResults[0];
            //如果用户拒绝了 跳转到设置界面  结束当前应用
            if(resultCode != PERMISSION_GRANTED) {
                ToastUtil.show(MainActivity.this,"没有拍照权限");
            } else {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                photoFile = new File(MyApplication.fileManager.baseFilePath,new Date().getTime()+".jpg");
                Uri photoImageUri = FileProvider.getUriForFile(MainActivity.this, "com.project.base.baseproject.FileProvider",photoFile);//通过FileProvider创建一个content类型的Uri
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoImageUri);//将拍取的照片保存到指定URI
                startActivityForResult(intent, Constant.SYSTEM_CAPTURE_REQUEST_CODE);
            }
        }
    }
    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择相册图片
        if(requestCode == Constant.SINGLE_SELECT_IMAGE_REQUEST_CODE) {
            if(resultCode == RESULT_OK) {
                loadingDialog.show();
                //获取选择的图片
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();
                if(StringUtil.isBlank(picturePath)) {
                    ToastUtil.show(MainActivity.this,"图片获取失败");
                    return;
                }
                //压缩图片
                Tiny.BitmapCompressOptions options = new Tiny.BitmapCompressOptions();
                options.height = DiviceInfo.dpToPx(MainActivity.this,60);
                options.width = options.height;
                Tiny.getInstance().source(picturePath).asBitmap().withOptions(options).compress(new BitmapCallback() {
                    @Override
                    public void callback(boolean isSuccess, Bitmap bitmap) {
                        userAvater.setImageBitmap(bitmap);
                        loadingDialog.close();
                    }
                });
            }
        }
        //拍照
        if(requestCode == Constant.SYSTEM_CAPTURE_REQUEST_CODE) {
            if(resultCode == RESULT_OK) {
                loadingDialog.show();
                //把图片保存到系统库 这样你这样图片就会出现在系统图片选择中
                try {
                    MediaStore.Images.Media.insertImage(MainActivity.this.getContentResolver(),
                            photoFile.getAbsolutePath(), photoFile.getName(), null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                //最后通知图库更新
                MainActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(photoFile)));
                //压缩图片
                Tiny.BitmapCompressOptions options = new Tiny.BitmapCompressOptions();
                options.height = DiviceInfo.dpToPx(MainActivity.this,60);
                options.width = options.height;
                Tiny.getInstance().source(photoFile).asBitmap().withOptions(options).compress(new BitmapCallback() {
                    @Override
                    public void callback(boolean isSuccess, Bitmap bitmap) {
                        userAvater.setImageBitmap(bitmap);
                        loadingDialog.close();
                    }
                });
            }
        }
    }
}
